package com.golxen.framework.db.dao;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

import java.sql.ResultSet;
import java.sql.SQLException;

public abstract class AbstractDaoImplByEntity<T extends AbstractDaoEntity> extends AbstractDaoImpl {

    public boolean add(T data) {
        data.setBeginWriteTime();
        boolean success = addData(data);
        if (success) {
            data.setNoneOption();
        }
        return success;
    }

    public boolean update(T data) {
        data.setBeginWriteTime();
        boolean success = updateData(data);
        if (success) {
            data.setNoneOption();
        }
        return success;
    }

    public boolean save(T data) {
        if (data == null) {
            return true;
        }

        if (!data.isDirty()) {
            return true;
        }

        if (data.isInsertOption()) {
            return add(data);
        } else if (data.isUpdateOption()) {
            return update(data);
        }
        return false;
    }

    protected T parse(ResultSet rs) throws SQLException {
        T data = parseData(rs);
        if (data != null) {
            data.setNoneOption();
        }
        return data;
    }

    /**
     * 添加
     * 
     * @param data 数据对象
     * @return
     */
    protected abstract boolean addData(T data);

    /**
     * 更新单个对象
     * 
     * @param data
     * @return
     */
    protected abstract boolean updateData(T data);

    /**
     * 解析单个对象
     * 
     * @param rs
     * @return
     */
    protected abstract T parseData(ResultSet rs) throws SQLException;

    protected <K> K parseJson(ResultSet rs, String key, TypeReference<K> type) throws SQLException {
        return JSONObject.parseObject(rs.getString(key), type);
    }

}
